<template>
  <el-tag
    v-for="tag in props.modelValue"
    type="warning"
    :key="tag"
    closable
    :disable-transitions="false"
    @close="handleClose(tag)"
  >
    {{ tag }}
  </el-tag>
  <el-input
    v-if="inputVisible"
    ref="InputRef"
    v-model.trim="inputValue"
    clearable
    @clear="clearInput"
    @keyup.enter="handleInputConfirm"
    @blur="handleInputConfirm"
  />
  <el-button v-else-if="!inputVisible && dynamicTags.length < maxNum" class="button-new-tag ml-1" @click="showInput">
    + 添加结束语
  </el-button>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch, computed, nextTick, onMounted } from 'vue'
  import { ElInput, ElMessage } from 'element-plus'

  const inputValue = ref<string>('')
  const dynamicTags = ref<string[]>([])
  const inputVisible = ref<boolean>(false)
  const InputRef = ref<InstanceType<typeof ElInput>>()
  const maxNum = ref<number>(100)   // 结束语 最多100个

  type Props = {
    modelValue: Array<string>|any
  }
  const props = withDefaults(defineProps<Props>(), {
    modelValue: []
  })

  const emit = defineEmits(['update:modelValue'])

  const handleClose = (tag: string) => {
    props.modelValue.splice(props.modelValue.indexOf(tag), 1)
    emit('update:modelValue', props.modelValue)

  }

  const showInput = () => {
    inputVisible.value = true
    nextTick(() => {
      InputRef.value!.input!.focus()
    })
  }

  const handleInputConfirm = () => {
    if(props.modelValue.includes(inputValue.value)){
      ElMessage.warning('请勿输入重复的结束语！')
      return
    }
    if (inputValue.value) {
      props.modelValue.push(inputValue.value)
    }
    inputVisible.value = false
    inputValue.value = ''
    emit('update:modelValue', props.modelValue)
  }

  const clearInput = ()=>{
    inputVisible.value = false
    inputValue.value = ''
  }

</script>
<style scoped lang="scss">
  .el-tag{
    margin-right: 8px;
    margin-right: 6px;
    background: #fffaf9;
    border-radius: 2px;
    border: 1px solid #ffc69e;
    color: #ff6b00;
  }
  .el-input{
    width: 140px;
  }
</style>
